//
//  COHomeViewController.swift
//  CocoProject
//
//  Created by Ruthless on 2023/8/20.
//

import UIKit
import JXSegmentedView
import QMUIKit
//import Presentr

class COHomeViewController: COBaseViewController {
    let squareVc = COHomeListViewController()
    let qaVc = COFoodViewController()
    
    override var navShow: Bool {
        false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        NotificationCenter.default.addObserver(self, selector: #selector(moneyChange), name: NSNotification.Name("CoinChange"), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        Self.getBalance()
        avatarImageView.kf.setImage(with: URL(string: COUserManager.userInfo?.sculpture ?? ""), for: .normal)
    }
    
    override func configUI() {
        view.addSubview(avatarImageView)
        view.addSubview(segmentView)
        view.addSubview(moneyButton)
        view.addSubview(contaierView)
        view.addSubview(createButton)
        
        avatarImageView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(20)
            make.top.equalToSuperview().offset(25 + statusBarHeight)
            make.width.height.equalTo(30)
        }
        
        segmentView.snp.makeConstraints { make in
            make.right.left.equalToSuperview().inset(70)
            make.centerY.equalTo(avatarImageView)
            make.height.equalTo(30)
        }
        
        moneyButton.snp.makeConstraints { make in
            make.left.equalTo(segmentView.snp.right).offset(0)
            make.right.equalToSuperview().offset(0)
            make.centerY.equalTo(avatarImageView)
        }
        
        contaierView.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.top.equalTo(segmentView.snp.bottom).offset(0)
        }
        
        createButton.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-bottomSafeHeight)
        }
    }

    private lazy var avatarImageView: UIButton = {
        let imgV = UIButton()
        imgV.layer.masksToBounds = true
        imgV.layer.cornerRadius = 15
        imgV.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        imgV.backgroundColor = .white
        return imgV
    }()

    private lazy var segmentView: JXSegmentedView = {
        let view = JXSegmentedView()
        view.dataSource = dataSource
        view.listContainer = contaierView
        view.delegate = self
        return view
    }()
    
    private lazy var dataSource: JXSegmentedTitleDataSource = {
        let dataSource = JXSegmentedTitleDataSource()
        dataSource.titles = ["Square", "Q&A area"]
        dataSource.titleNormalFont = .bold(18)
        dataSource.titleSelectedFont = .bold(22)
        dataSource.titleNormalColor = .rgba(61, 51, 94)
        dataSource.titleSelectedColor = .white
        
        return dataSource
    }()
    
    private lazy var moneyButton: QMUIButton = {
        let btn = QMUIButton()
        btn.spacingBetweenImageAndTitle = 5
        btn.imagePosition = .left
        btn.setImage(UIImage(named: "金币"), for: .normal)
        let num = UserDefaults.standard.integer(forKey: "\(COUserManager.userInfo?.id ?? 0)---coin")
        btn.setTitle("\(num)", for: .normal)
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
    
    private lazy var contaierView: JXSegmentedListContainerView = {
        let view = JXSegmentedListContainerView(dataSource: self)
        return view
    }()
    
    private lazy var createButton: UIButton = {
        let btn = UIButton()
        btn.setImage(UIImage(named: "编组 4"), for: .normal)
        btn.addTarget(self, action: #selector(clickButton), for: .touchUpInside)
        return btn
    }()
}

extension COHomeViewController: JXSegmentedListContainerViewDataSource {
    func numberOfLists(in listContainerView: JXSegmentedListContainerView) -> Int {
        2
    }
    
    func listContainerView(_ listContainerView: JXSegmentedListContainerView, initListAt index: Int) -> JXSegmentedListContainerViewListDelegate {
        [squareVc, qaVc][index]
    }
    
    
}

extension COHomeViewController: JXSegmentedViewDelegate {
    @objc
    private func clickButton(_ btn: UIButton) {
        if btn == createButton {
            let vc = COCreateViewController()
            vc.clickAction = {[weak self] tag in
                self?.dismiss(animated: false, completion: {
                    let vc = COHomeCreateViewController(type: tag)
                    
                    vc.title = tag == 0 ? "Post Square" : "Post Q&A area"
                    self?.navigationController?.pushViewController(vc, animated: true)
                })
            }
            self.present(vc, animated: true)
        } else if btn == avatarImageView {
            let vc = COMineViewController()
            self.navigationController?.pushViewController(vc)
        } else if btn == moneyButton {
            let vc = COWalletController()
            self.navigationController?.pushViewController(vc, animated: true)
        }
    }
    
    static func getBalance() {
        CONetwork.sendRequest(provider: loginProvider, target: .balance) { text in
            guard let dic = text.dic else {
                return
            }
            
            UserDefaults.standard.setValue(dic["coins"], forKey: "\(COUserManager.userInfo?.id ?? 0)---coin")
            UserDefaults.standard.synchronize()
            NotificationCenter.default.post(name: NSNotification.Name("CoinChange"), object: nil)
        } failedBlock: { _, _ in
            
        }
    }
    
    @objc
    private func moneyChange() {
        let num = UserDefaults.standard.integer(forKey: "\(COUserManager.userInfo?.id ?? 0)---coin")
        moneyButton.setTitle("\(num)", for: .normal)
    }
    
}
